﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MailServer {
    public partial class FCliente : Form {
        private Server.Server server;
        private Client.Client client;

        private string pathClient;

        public FCliente() {
            InitializeComponent();
            //lbCorreo.Items.AddRange(new Object[] { "First Item", "Second Item" });
            lbCorreo.DrawMode = DrawMode.OwnerDrawFixed;
        }

        private void cargarDatos() {
            server = new Server.Server(txRutaS.Text);
        }

        private void cargarCorreos() {
            client = new Client.Client(server, txUsuario.Text, pathClient);
            client.SyncMessages();
            List<Message.Message> lm = client.ListMessages();
            int i = lbCorreo.SelectedIndex;
            lbCorreo.Items.Clear();
            txCorreo.Text = "";
            foreach(Message.Message m in lm) {
                lbCorreo.Items.Add(new WMessage() { Message = m });
            }
            if(i > -1 && i < lbCorreo.Items.Count)
                lbCorreo.SelectedIndex = i;
        }

        private void cargarCorreosFrom() {
            if(client == null) return;
            client = new Client.Client(server, txUsuario.Text, pathClient);
            client.SyncMessages();
            List<Message.Message> lm = client.ListMessagesFrom(txDest.Text);
            lbCorreo.Items.Clear();
            txCorreo.Text = "";
            foreach(Message.Message m in lm) {
                lbCorreo.Items.Add(new WMessage() { Message = m });
            }
        }

        private void btRutaS_Click(object sender, EventArgs e) {
            od1.CheckFileExists = true;
            if(od1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                txRutaS.Text = od1.FileName;
                try {
                    cargarDatos();
                } catch {
                    MessageBox.Show("Seleccione un archivo válido", "Cliente", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                txUsuario.Enabled = true;
                btVerCorreo.Enabled = true;
                txUsuario.ReadOnly = false;
                lbCorreo.Items.Clear();
                txCorreo.Text = "";
                txDest.Text = "";
                txUsuario.Text = "";
            }
        }

        private void btVerCorreo_Click(object sender, EventArgs e) {
            if(string.IsNullOrEmpty(txUsuario.Text)) {
                MessageBox.Show("Introduzca un usuario válido", "Cliente", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            od1.CheckFileExists = false;
            if(od1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                pathClient = od1.FileName;
            } else
                return;
            if(!string.IsNullOrEmpty(txUsuario.Text)) {
                if(!server.UserExists(txUsuario.Text)) {
                    MessageBox.Show("Usuario no registrado en el servidor", "Correos", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                try {
                    cargarCorreos();
                } catch {
                    MessageBox.Show("Seleccione un archivo válido", "Cliente", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                gbMsg.Enabled = true;
                txUsuario.ReadOnly = true;
                btVerCorreo.Enabled = false;
                tm1.Enabled = true;
            }
        }

        private void button2_Click(object sender, EventArgs e) {
            cargarCorreos();
        }

        private class WMessage {
            public Message.Message Message { get; set; }
            public override string ToString() {
                string[] s = Message.ToString().Split('\r');
                return s[0].Trim() + ", " + s[2].Trim();
            }
        }

        private void lbCorreo_DrawItem(object sender, DrawItemEventArgs e) {
            try {
                if(!client.IsReaded(((WMessage)lbCorreo.Items[e.Index]).Message)) {
                    e.DrawBackground();
                    e.Graphics.DrawString(lbCorreo.Items[e.Index].ToString(), new Font("Calibri", 9, FontStyle.Bold), Brushes.Black, e.Bounds);
                    e.DrawFocusRectangle();
                } else {
                    e.DrawBackground();
                    e.Graphics.DrawString(lbCorreo.Items[e.Index].ToString(), new Font("Calibri", 9), Brushes.Black, e.Bounds);
                    e.DrawFocusRectangle();
                }
            } catch { }
        }

        private void lbCorreo_SelectedIndexChanged(object sender, EventArgs e) {
            int i = lbCorreo.SelectedIndex;
            if(i > -1) {
                client.SetReaded(((WMessage)lbCorreo.Items[i]).Message);
                txCorreo.Text = ((WMessage)lbCorreo.Items[i]).Message.ToString();
            }
        }

        private void button3_Click(object sender, EventArgs e) {
            int i = lbCorreo.SelectedIndex;
            if(i > -1 && MessageBox.Show("¿Eliminar el mensaje?", "Cliente", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK) {
                client.RemoveMessage(((WMessage)lbCorreo.Items[i]).Message);
                cargarCorreos();
            }
        }

        private void tm1_Tick(object sender, EventArgs e) {
            try {
                cargarCorreos();
            } catch(Exception ex) { }
        }

        private void button1_Click(object sender, EventArgs e) {
            if(client == null) {
                return;
            }
            FCorreo f = new FCorreo(client);
            f.ShowDialog(this);
            f.Dispose();
            cargarCorreos();
        }

        private void btBuscar_Click(object sender, EventArgs e) {
            try {
                cargarCorreosFrom();
            } catch { }
        }

    }
}
